package com.kwan.x_im.data.db;

import android.content.Context;
import android.content.res.AssetManager;
import android.net.Uri;
import android.util.Log;


import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import timber.log.Timber;


/**
 * @author kwan
 * @date 2023/2/13 11:39
 * @Describe
 */
public class DBManger {


	public XDataBase dataBase;

	private Context context;

	public void init(Context context) {
		Timber.e("init %s", Thread.currentThread().getName());
		this.context = context;
		dataBase = Room.databaseBuilder(context, XDataBase.class, "book.db")
				.allowMainThreadQueries()
				.addCallback(new RoomDatabase.Callback() {
					@Override
					public void onCreate(@NonNull SupportSQLiteDatabase db) {
						super.onCreate(db);
						Timber.e("onCreate " + Thread.currentThread().getName());
					}

					@Override
					public void onOpen(@NonNull SupportSQLiteDatabase db) {
						super.onOpen(db);
						Timber.e("onOpen " + Thread.currentThread().getName());
					}
				})
				.build();
		Timber.e("init over%s", Thread.currentThread().getName());

	}

	public XDataBase getDataBase() {
		return dataBase;
	}

//	public List<BookBean> getAllBook() {
//		return dataBase.xDao().getAllBooks();
//	}
//
//	public List<BookBean> getAllBook(long... id) {
//		return dataBase.xDao().getAllBooks(id);
//	}
//
//	public void insertBooks(BookBean... books) {
//		dataBase.xDao().insertBook(books);
//	}
//
//	public void updateBooks(BookBean... books) {
//		dataBase.xDao().updateBooks(books);
//	}
//
//
//	public List<Chapter> getChapter(long bid) {
//		return dataBase.xDao().getChapter(bid);
//	}
//
//	public void insertChapters(Chapter... chapters) {
//		dataBase.xDao().insertChapter(chapters);
//	}
//
//	public void updateChapters(Chapter... chapters) {
//		dataBase.xDao().updateChapters(chapters);
//	}
//
//
//	public void updateHistory(BookHistory histories) {
//		dataBase.xDao().updateHistory(histories);
//	}
//
//	public List<BookHistory> getAllHistory() {
//		return dataBase.xDao().getAllHistory();
//	}
//
//	public void deleteHistory(BookHistory... histories) {
//		dataBase.xDao().deleteHistory(histories);
//	}
//
//	public static List<BookBean> bookBeans;

	public void initBook() {
//		try {
//			Config.createConfig(context);
//			PageFactory.createPageFactory(context);
//			if (SPUtils.getInstance().getBoolean("initBook")) {
//				bookBeans = getAllBook();
//				ThreadUtils.runOnUiThreadDelayed(new Runnable() {
//					@Override
//					public void run() {
//
//						account = GoogleSignIn.getLastSignedInAccount(context);
//
//						if (account == null) {
//							Log.e("kwan", "以前没有登录");
//							ActivityUtils.startActivity(LoginActivity.class);
//						} else {
//							Log.e("kwan", "以前登录过");
//							String personName = account.getDisplayName();
//							String personGivenName = account.getGivenName();
//							String personFamilyName = account.getFamilyName();
//							String personEmail = account.getEmail();
//							String personId = account.getId();
//							Uri personPhoto = account.getPhotoUrl();
//							Log.e("kwan", "IdToken:" + account.getIdToken());
//							Log.e("kwan", "Id:" + account.getId() + "|Email:" + account.getEmail() + "|personName:" + personName);
//							Log.e("kwan", "personGivenName:" + personGivenName + "|personFamilyName:" + personFamilyName + "|personName:" + personName);
//							ActivityUtils.startActivity(MainActivity.class);
//							HttpTokenManager.getInstance().setCacheToken(SPUtils.getInstance(account.getId()).getString("token"));
//						}
//
//						ActivityUtils.finishActivity(SplashActivity.class);
//					}
//				}, 2000);
//				return;
//			}
//
//			bookBeans = new ArrayList<>();
//
//			AssetManager mAssetManger = context.getAssets();
//			// 获取assets目录下的所有文件及有文件的目录名
//			String[] books = mAssetManger.list("book");
//			//load("file:///android_asset/image_test.png")
//			if (books.length > 0) {//如果是目录,如果是具体文件则长度为0
//				int bookId = 0;
//				for (String book : books) {
//					bookId++;
//					String[] pages = mAssetManger.list("book/" + book);
//					BookBean bookBean = new BookBean();
//					bookBean.id = bookId;
//					bookBean.setTitle(book);
//					//bookBean.setPath("file:///android_asset/book/" + book);
//					List<Chapter> chapters = new ArrayList<>();
//					boolean first = true;
//
//					for (String page : pages) {
//
//						if (page.endsWith(".jpg")) {
//							bookBean.setImage("file:///android_asset/book/" + book + "/" + page);
//						} else {//章节了
//							try {
//								String strPageIndex = page.split("of")[0].replace("Page", "").trim();
//								//Log.e("kwan","strPageIndex:"+strPageIndex);
//								int index = Integer.parseInt(strPageIndex);
//								//Log.e("kwan","index:"+index);
//								//Log.e("kwan", "page:" + page + " strPageIndex:" + strPageIndex);
//								Chapter chapter = new Chapter("book/" + book + "/" + page,  index);
//								chapter.setBookId(bookId);
//								chapter.setLock(true);
//								chapters.add(chapter);
//								if (first) {
//									first = false;
//									String content = getAssetsData("book/" + book + "/" + page);
//									String decrypt = AESUtils.decode(content, "ducknovel2023100").split("\n")[2];
//									Log.e("kwan", "content:" + decrypt);
//									bookBean.setContent(decrypt);
//								}
//
//							} catch (Exception e) {
//								Log.e("kwan", "error page:" + book + " " + page);
//								Log.e("kwan", "error page:" + e.getMessage());
//							}
//						}
//					}
//
//					Collections.sort(chapters);
//					bookBean.setChapters(chapters);
//					insertChapters(chapters.toArray(new Chapter[]{}));
//					bookBeans.add(bookBean);
//				}
//
//				insertBooks(bookBeans.toArray(new BookBean[]{}));
//				SPUtils.getInstance().put("initBook", true);
//			}
//
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//
//
//		ThreadUtils.runOnUiThreadDelayed(new Runnable() {
//			@Override
//			public void run() {
//				ActivityUtils.startActivity(LoginActivity.class);
//				ActivityUtils.finishActivity(SplashActivity.class);
//			}
//		}, 1500);
	}

	private String getAssetsData(String path) {
		String result = "";
		try {
			InputStream is = context.getAssets().open(path);
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream stream = new ByteArrayOutputStream(is.available());
			int byteCount;
			while ((byteCount = is.read(buffer)) != -1) {//循环从输入流读取 buffer字节
				stream.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
			}
			stream.flush();//刷新缓冲区
			result = stream.toString();
			is.close();
			stream.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("fuck", "error");
			return result;
		}
	}


//	public static List<BookBean> getRandomBooks(int size) {
//
//		if (size > bookBeans.size())
//			size = bookBeans.size();
//
//		List<BookBean> list = new ArrayList<>(bookBeans);
//		Collections.shuffle(list);
//		return list.subList(0, size);
//	}


}
